package com.vcc.boss.core.aspect;

import com.vcc.core.annotations.VerifyPermission;
import com.vcc.core.exception.PermissionException;
import com.vcc.data.entity.BossRolePermission;
import com.vcc.data.entity.Permission;
import com.vcc.service.service.BossRolePermissionService;
import com.vcc.service.service.BossRoleService;
import com.vcc.service.service.BossUserService;
import com.vcc.service.service.PermissionService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Aspect
public class VccControllerAspect {

    private static final Logger logger = LoggerFactory.getLogger(VccControllerAspect.class);

    @Autowired
    private BossUserService bossUserService;
    @Autowired
    private BossRoleService bossRoleService;
    @Autowired
    private BossRolePermissionService bossRolePermissionService;
    @Autowired
    private PermissionService permissionService;


    //controller层切点
    @Pointcut("@annotation(com.vcc.core.annotations.VerifyPermission)")
    public void controllerAspect() {
    }

    ;

    @Before("controllerAspect()")
    public void deBefore(JoinPoint joinPoint) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Long userId = (Long) request.getAttribute("userId");
        List<BossRolePermission> bossRolePermissions = bossRolePermissionService.listByUserId(userId);
        List<Permission> permissionList = permissionService.list();
        List<String> permissions = bossRolePermissions.stream().map(it -> {
            Permission permission = permissionList.stream().filter(p -> p.getId().equals(it.getPermissionId())).findFirst().orElseThrow(() -> new PermissionException("解析权限发生错误"));
            if (it.getStatus().equals(0)) {
                return permission.getCode();
            } else {
                return "";
            }
        }).filter(it -> !Objects.equals(it, "")).distinct().toList();
        //请求的IP
        String ip = request.getRemoteAddr();
        try {
            //*========控制台输出=========*//
            String[] description = getControllerMethodDescription(joinPoint);
            List<String> intersectionList = permissions.stream().filter(it-> Arrays.asList(description).contains(it)).collect(Collectors.toList());
            logger.info("匹配到的权限是:{}",intersectionList);
            if (intersectionList.isEmpty()){
                throw new PermissionException("权限不足，无法调用");
            }
        } catch (Exception e) {
            throw e instanceof PermissionException ? e : new PermissionException("全新解析发生错误，请连续管理人员");
        }
    }


    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String[] getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String[] description = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(VerifyPermission.class).verifyCodes();
                    break;
                }
            }
        }
        return description;
    }

}
